import { NextRequest, NextResponse } from 'next/server'
import { getTools, getReviews, getFavorites } from '@/lib/database'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const toolId = params.id
    
    // 获取所有工具
    const tools = await getTools(request)
    const tool = tools.find(t => t.id === toolId)
    
    if (!tool) {
      return NextResponse.json(
        { error: '工具不存在' },
        { status: 404 }
      )
    }

    // 获取工具的评价和收藏数据
    const reviews = await getReviews()
    const favorites = await getFavorites()
    
    // 计算工具的统计信息
    const toolReviews = reviews.filter(review => review.toolId === toolId)
    const toolFavorites = favorites.filter(favorite => favorite.toolId === toolId)
    
    // 计算平均评分
    const averageRating = toolReviews.length > 0 
      ? toolReviews.reduce((sum, review) => sum + review.rating, 0) / toolReviews.length
      : 0

    // 构建完整的工具信息
    const toolWithStats = {
      ...tool,
      _count: {
        reviews: toolReviews.length,
        favorites: toolFavorites.length
      },
      averageRating: Math.round(averageRating * 10) / 10, // 保留一位小数
      reviews: toolReviews,
      favorites: toolFavorites
    }

    return NextResponse.json({
      success: true,
      data: toolWithStats
    })
  } catch (error) {
    console.error('获取工具详情失败:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}
